<?php
declare (strict_types = 1);

namespace app\middleware;

use app\exception\AuthException;
use app\exception\BaseException;
use think\facade\Cache;

class AuthMiddleware
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure $next
     * @throws AuthException
     * @throws BaseException
     */
    public function handle(\think\Request $request, \Closure $next)
    {
        if($request->baseUrl() != '/account/login' && !$request->isGet()){
            try{
                $admin = $request->admin;

                if ($admin['uid'] == 1) {
                    return $next($request);
                }

                $path = strtolower($request->baseUrl());
                $auth = Cache::get('auth_'.$admin['seller_id'].'_'.$admin['uid'],[]);
                $allowPath = array_column($auth,'path');
                $allowPath = array_map(function ($item){
                    return  strtolower($item);
                },$allowPath);
                $allowPath = array_merge($allowPath,config('rbac.skip_auth'));
                if(!in_array($path,$allowPath)){
                    throw new AuthException();
                }
            }catch(\Exception $e){
                throw new BaseException($e->getMessage());
            }
        }
        return $next($request);
    }
}
